#coding=utf8
import math
from keras.models import Model
from keras.layers import Dense
from keras.applications.resnet50 import ResNet50
from keras.preprocessing.image import ImageDataGenerator




# 训练的batch_size
batch_size = 16
# 训练的epoch
epochs = 20

# 图像Generator，用来构建输入数据
# channel last
train_datagen = ImageDataGenerator(
    width_shift_range=0.1,
    height_shift_range=0.1,
    zoom_range=0.2,
    horizontal_flip=True)

# 从文件中读取数据，目录结构应为train下面是各个类别的子目录，每个子目录中为对应类别的图像
train_generator = train_datagen.flow_from_directory('/media/hszc/data/BaiduImage/dataset/trainall', target_size=(299, 299), batch_size=batch_size)

# 输出类别信息
print train_generator.class_indices

# 生成测试数据
val_datagen = ImageDataGenerator()
validation_generator = val_datagen.flow_from_directory('./validation', target_size=(299, 299), batch_size=batch_size)

# create the base pre-trained model
base_model = Xception(weights='imagenet', include_top=False)

# add a global spatial average pooling layer
x = base_model.output
x = GlobalAveragePooling2D()(x)
# let's add a fully-connected layer
x = Dense(1024, activation='relu')(x)
# and a logistic layer -- let's say we have 200 classes
predictions = Dense(100, activation='softmax')(x)

# this is the model we will train
model = Model(inputs=base_model.input, outputs=predictions)

# first: train only the top layers (which were randomly initialized)
# i.e. freeze all convolutional InceptionV3 layers
for layer in base_model.layers:
    layer.trainable = False

model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

# 训练模型
model.fit_generator(train_generator, steps_per_epoch=1006, epochs=3, validation_data=validation_generator,
                    validation_steps=batch_size)

# at this point, the top layers are well trained and we can start fine-tuning
# convolutional layers from inception V3. We will freeze the bottom N layers
# and train the remaining top layers.

# let's visualize layer names and layer indices to see how many layers
# we should freeze:
for i, layer in enumerate(base_model.layers):
    print(i, layer.name)
# we chose to train the top 2 inception blocks, i.e. we will freeze
# the first 172 layers and unfreeze the rest:
for layer in model.layers[:115]:
    layer.trainable = False
for layer in model.layers[115:]:
    layer.trainable = True

# we need to recompile the model for these modifications to take effect
# we use SGD with a low learning rate
from keras.optimizers import SGD

# model.compile(optimizer=SGD(lr=0.0001, momentum=0.9), loss='categorical_crossentropy')

# we train our model again (this time fine-tuning the top 2 inception blocks
# alongside the top Dense layers
model.compile(

    loss='categorical_crossentropy',
    optimizer=SGD(lr=1e-4, decay=1e-6, momentum=0.9, nesterov=True),
    metrics=['accuracy'])
# 训练模型
model.fit_generator(train_generator, steps_per_epoch=1006, epochs=20, validation_data=validation_generator,
                    validation_steps=batch_size)

model.save_weights('weights.h5')


#预测

